package com.xidian.zhiancloud.controller.ledgerManagerment.relatedPart;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xidian.zhiancloud.constant.LedgerManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.ledgerManagerment.relatedParty.RelatedPartyDocQO;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.vo.ledgerManagerment.relatedParty.RelatedPartyDocVO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.RelatedPartyDoc;
import com.xidian.zhiancloud.service.ledgerManager.relatedPart.RelatedPartyDocService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 台账管理 相关方管理 相关方档案
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:27
 */
@RestController
@RequestMapping("/RelatedPartyDoc")
public class RelatedPartyDocController extends BaseController {
    @Autowired
    private RelatedPartyDocService relatedPartyDocService;

    @Autowired
    private UserService userService;

    /**
     * 增加一个相关方对象
     *
     * @param relatedPartyDoc 相关方对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(RelatedPartyDoc relatedPartyDoc) {
        relatedPartyDoc.setCompanyId(getSessionUserCompanyId());
        relatedPartyDoc.setCreatorId(getSessionUserid());
        relatedPartyDoc.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = relatedPartyDocService.save(relatedPartyDoc);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id查找一个相关方对象
     *
     * @param id 相关方对象的id
     * @return 相关方档案对象
     */
    @GetMapping("/getById")
    public ResultDTO<RelatedPartyDoc> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(relatedPartyDocService.getById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id数组删除相关方对象
     *
     * @param ids 相关方id数组
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = relatedPartyDocService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id修改相关方对象
     *
     * @param relatedPartyDoc 相关方对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(RelatedPartyDoc relatedPartyDoc) {
        relatedPartyDoc.setCreatorId(null);
        relatedPartyDoc.setCompanyId(null);
        relatedPartyDoc.setCreateTime(null);
        Boolean res = relatedPartyDocService.updateById(relatedPartyDoc);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据条件查询相关方列表
     *
     * @param relatedPartyDocQO 查询参数
     * @return 相关方档案列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<RelatedPartyDocVO>> getListByQueryObject(RelatedPartyDocQO relatedPartyDocQO) {
        if (relatedPartyDocQO.getCurrent() == null || relatedPartyDocQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        relatedPartyDocQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(relatedPartyDocService.getListByQO(relatedPartyDocQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("相关方档案导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<RelatedPartyDoc> list = relatedPartyDocService.listByIds(Arrays.asList(ids));
        List<RelatedPartyDocVO> ans = new LinkedList<>();
        list.forEach(t -> {
            RelatedPartyDocVO vo = new RelatedPartyDocVO();
            BeanUtils.copyProperties(t, vo);
            SysUser sysUser = userService.getById(vo.getCreatorId());
            vo.setCreatorName(sysUser == null ? "该用户已被删除" : sysUser.getName());
            vo.setEnterpriseTypeName(LedgerManagementConstant.EnterpriseType.get(vo.getEnterpriseType()));
            vo.setInCooperationName(LedgerManagementConstant.InCooperation.get(vo.getInCooperation()));
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), RelatedPartyDocVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<RelatedPartyDocVO> list = EasyExcel.read(file.getInputStream()).head(RelatedPartyDocVO.class).sheet().doReadSync();
        List<RelatedPartyDoc> ans = new LinkedList<>();
        list.forEach(vo -> {
            RelatedPartyDoc doc = new RelatedPartyDoc();
            BeanUtils.copyProperties(vo, doc);
            doc.setCreatorId(getSessionUserid());
            doc.setCompanyId(getSessionUserCompanyId());
            doc.setInCooperation(LedgerManagementConstant.InCooperation.indexOf(vo.getInCooperationName()));
            doc.setEnterpriseType(LedgerManagementConstant.EnterpriseType.indexOf(vo.getEnterpriseTypeName()));
            doc.setCreateTime(new Date(System.currentTimeMillis()));
            ans.add(doc);
        });
        list.forEach(System.out::println);
        Boolean res = relatedPartyDocService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }


    @GetMapping("/getList")
    public ResultDTO<Map<Long, String>> getList() {
        Long companyId = getSessionUserCompanyId();
        return ResultDTO.successOf(relatedPartyDocService.getList(companyId), GeneralResponseEnums.SUCCESS);
    }
}
